package teaching.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessEmployeeRecord extends Employee {

  public static final int SIZE = 42;

  public RandomAccessEmployeeRecord() {
    super();
  }

  public RandomAccessEmployeeRecord(Integer id, String name, Double salary) {
    super(id, name, salary);
  }

  private String readName(RandomAccessFile in) throws IOException {
    char temp;
    char[] name = new char[15];

    for (int count = 0; count < name.length; count++) {
      temp = in.readChar();
      name[count] = temp;
    }
    return new String(name).replace('\0', ' ').trim();
  }

  private void writeName(String name, RandomAccessFile out) throws IOException {
    StringBuffer stringBuffer = null;
    if (name != null) {
      stringBuffer = new StringBuffer(name);
    } else {
      stringBuffer = new StringBuffer(15);
    }
    stringBuffer.setLength(15);

    out.writeChars(stringBuffer.toString());
  }

  /**
   * .
   * 
   * @param in
   *          ��������
   * @throws IOException
   *           ��������쳣
   */
  public void read(RandomAccessFile in) throws IOException {
    this.setId(in.readInt());
    this.setName(readName(in));
    this.setSalary(in.readDouble());
  }

  /**
   * .
   * 
   * @param out
   *          �������
   * @throws IOException
   *           ��������쳣
   */
  public void write(RandomAccessFile out) throws IOException {
    out.writeInt(this.getId());
    writeName(this.getName(), out);
    out.writeDouble(this.getSalary());
  }
}
